package com.ly.mpayment.rest.recharge;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.LinkedBlockingQueue;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.*;
import com.ly.mpayment.persist.entity.ele.EleRecord;
import com.ly.mpayment.persist.service.callorder.ICallOrderService;
import com.ly.mpayment.persist.service.mobile.IMobileService;
import com.ly.mpayment.rest.system.DownRechargeFlowRest;
import com.ly.mpayment.rest.system.entity.ManualRechargeOrder;
import com.ly.mpayment.rest.up.OrderHandler;
import com.ly.mpayment.rest.up.hunanjb.HuNanJob;
import com.ly.mpayment.rest.up.qinghaiyd.QingHaiYd;
import com.ly.mpayment.rest.up.qinghaiyd.YiDongEntity;
import org.apache.log4j.Logger;
import org.mortbay.util.UrlEncoded;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.downshopproduct.IDownShopProductService;
import com.ly.mpayment.persist.service.matchingstrategy.IMatchingStrategyService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.persist.service.upshoppro.IUpShopProService;
import com.ly.mpayment.persist.service.yidong.IMobileOrdersService;
import org.springframework.stereotype.Component;


/**
 * 下游提交的订单队列
 *
 */
@Component
public class OrderProcessing {
	static Logger logger = Logger.getLogger(OrderProcessing.class);

	public static LinkedBlockingQueue<DownRechargeFlow> callResultQueue = new LinkedBlockingQueue<>();

	/**
	 * 订单检查
	 */
	public static LinkedBlockingQueue<YiDongEntity> yiDongQueue = new LinkedBlockingQueue<>();

	/**
	 * 订单提交
	 */
	public static LinkedBlockingQueue<YiDongEntity> yiDongQueuePlace = new LinkedBlockingQueue<>();

	/**
	 * 任务队列
	 */
	public static LinkedBlockingQueue<DownRechargeFlow> taskOrder = new LinkedBlockingQueue<>();

	/**
	 * 湖南工号队列
	 */
	public static LinkedBlockingQueue<UpOrder> hunanjobOrder = new LinkedBlockingQueue<>();



	@Autowired
	IDownShopProductService productService;

	@Autowired
	IDownRechargeFlowService flowService;

	@Autowired
	IUpShopProService upShopService;

	@Autowired
	IUporderService upOrderService;

	@Autowired
	IDownShopInfoService shopService;

	@Autowired
	IUpShopInfoService upShopInfoService;

	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;

	@Autowired
	IMobileOrdersService ordersService;

	@Autowired
	IMatchingStrategyService matchStrategyService;

	@Autowired
	RechargeRest rechargeRest;

	@Autowired
	IMobileService mobileService;

	@Autowired
	OrderThread orderThread;

	@Autowired
	OrderHandler orderHandler;

	@Autowired
	private DownRechargeFlowRest downRechargeFlowRest;

	@Autowired
	ICallOrderService callOrderService;

	@Autowired
	private QingHaiYd qingHaiYd;

	@Autowired
	private HuNanJob huNanJob;

	@SuppressWarnings("unused")
	private void order(){
		logger.info("order处理启动");
		//orderFlow2();
		//orderFlow1();
		orderFlow();
		successOrder();
		failtOrder();
		manualOrder();
		pressOrder();
		callOrder();
		qhyd();
		placeOrder();
		queryTask();
		handlerHuNan();
	}

	private void handlerHuNan(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true){
					UpOrder order = null;
					try {
						order = OrderProcessing.hunanjobOrder.take();
						try {
							UpOrder upOrder = upOrderService.findByIdWait(order.getUporderuuid());
							if(upOrder != null && upOrder.getStatus() == Config.status[5]){
								UpShopInfo shopInfo = upShopInfoService.findByUserId(upOrder.getUserOrder().getUseruuid());
								if(shopInfo != null){
									logger.info("处理等待充值的订单:"+upOrder.getUpphonenum());
									huNanJob.commitOrder(upOrder,shopInfo);
								}
							}
						}catch (Exception e){
							e.printStackTrace();
							if(order != null){
								OrderProcessing.hunanjobOrder.add(order);
							}
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				}
			}
		}).start();
	}

	/**
	 * 成功订单
	 */
	private void successOrder(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true){
					UpOrder flow = null;
					try {
						flow = RechargeRest.successUpOrder.take();
						try {
							UpOrder upOrder = upOrderService.findByIdSuccess(flow.getUporderuuid());
							if(upOrder != null &&  (upOrder.getStatus() == Config.status[0] || upOrder.getStatus() == Config.status[10]
									|| upOrder.getStatus() == Config.status[11])){
								logger.info("处理订单成功的订单:"+upOrder.getUpphonenum());
								orderHandler.orderHanlderSuccess(upOrder,flow.getRemark() != null ? flow.getRemark().replace("null","") : flow.getRemark());
							}
						}catch (Exception e){
							e.printStackTrace();
							if(flow != null){
								RechargeRest.successUpOrder.add(flow);
							}
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				}
			}
		}).start();
	}

	/**
	 * 手动批量充值
	 */
	private void manualOrder(){

		/**
		 * 手动批量提单
		 */
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true){
					try {
						ManualRechargeOrder manualOrder = AutoOrderService.manualOrder.take();

//						Mobile mobile = mobileService.findPhone(manualOrder.getPhone().substring(0, 7));
//						if (mobile == null) {
//							logger.info("restBatch_error号码地市不存在,请添加:"+ manualOrder.toString());
//						}
						DownShopInfo downShopInfo = shopService.findShopInfoByUuid(manualOrder.getUid());
						if(downShopInfo == null){
							logger.info("分销商不存在:"+ manualOrder.toString());
							downRechargeFlowRest.createFailt(manualOrder,"分销商不存在");
							continue;
						}

						String operatoruid = manualOrder.getOperatoruid();

						List<DownShopProduct> downShopProduct = productService.findByUuidAndCity(manualOrder.getUid(), "","",manualOrder.getMoney(),manualOrder.getBusCode(),operatoruid);
						if(downShopProduct == null || downShopProduct.size() == 0){
							//查询省份产品
							downShopProduct = productService.findByUuidAndProvice(manualOrder.getUid(),manualOrder.getMoney(),"",manualOrder.getBusCode(),operatoruid);
							if(downShopProduct == null || downShopProduct.size() == 0){
								//按地市查询没有产品后检查全国是否有
								downShopProduct = productService.findByGlobalCountry(manualOrder.getUid(),manualOrder.getMoney(),manualOrder.getBusCode(),operatoruid);
								if(downShopProduct == null || downShopProduct.size() == 0){
									logger.info("restBatch_error:"+ manualOrder.getPhone()+",没有配置产品");
									downRechargeFlowRest.createFailt(manualOrder,"没有配置产品");
									continue;
								}
							}
						}

						manualOrder.setPid(downShopProduct.get(0).getDownprouuid());
						manualOrder.setSign(MD5.md5(StringSort.doSign(JSONObject.parseObject(JSONObject.toJSONString(manualOrder)))
								+"&key="+downShopInfo.getDownkey()));

						logger.info("充值手机号:"+JSONObject.toJSONString(manualOrder));

						String result = rechargeRest.rechargeOrder(JSONObject.toJSONString(manualOrder),null,false);
						if(result != null){
							JSONObject jsonObject = JSONObject.parseObject(result);
							if(!jsonObject.getString("code").equals("1000") && !jsonObject.getString("code").equals("1201")){
								downRechargeFlowRest.createFailt(manualOrder,jsonObject.getString("message"));
							}
						}
						logger.info("充值结果:"+result);
					} catch (Exception e) {
						e.printStackTrace();
						logger.info(e.getMessage());
					}
				}
			}
		}).start();
	}

	/**
	 * 压单
	 */
	private void pressOrder(){
		/**
		 * 压单处理
		 */
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true){
					UpOrder flow = null;
					try {
						flow = RechargeRest.pressUpOrder.take();
						try {
							//查询压单或者人工重提的订单
							UpOrder upOrder = upOrderService.findByPressOrder(flow.getUporderuuid());
							if(upOrder != null && (upOrder.getStatus() == Config.status[10] || upOrder.getStatus() == Config.status[11])){
								//提修改订单状态为充值中
								upOrder.setStatus(Config.status[0]);
								upOrderService.updateOrder(upOrder);
								logger.info("处理压单或人工订单:"+upOrder.getUpphonenum());
								UpShopInfo upShopInfo = upShopInfoService.findByUserId(upOrder.getUserOrder().getUseruuid());
								taskExecutor.execute(new Runnable() {
									@Override
									public void run() {
										orderHandler.commitOrder(upOrder,upShopInfo);
									}
								});
							}else{
								logger.info("压单已经处理:"+flow.getUpphonenum());
							}
						}catch (Exception e){
							e.printStackTrace();
							if(flow != null){
								RechargeRest.pressUpOrder.add(flow);
							}
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	/**
	 * 失败订单
	 */
	private void failtOrder(){
		/**
		 * 失败订单
		 */
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true){
					UpOrder flow = null;
					try {
						flow = RechargeRest.failtUpOrder.take();
						try {
							UpOrder upOrder = upOrderService.findByIdFail(flow.getUporderuuid());

							if(upOrder != null && (upOrder.getStatus() == Config.status[0] || upOrder.getStatus() == Config.status[10]
									|| upOrder.getStatus() == Config.status[11] || upOrder.getStatus() == Config.status[1]
									|| upOrder.getStatus() == Config.status[5])){
								logger.info("处理失败订单:"+upOrder.getUpphonenum());
								//检查订单是否失败
								orderHandler.orderHanlderFailt(upOrder,flow.getRemark() != null ? flow.getRemark().replace("null","") : flow.getRemark());
							}
						}catch (Exception e){
							e.printStackTrace();
							if(flow != null){
								RechargeRest.failtUpOrder.add(flow);
							}
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	/**
	 * 回调订单
	 */
 	private void callOrder(){
		/**
		 * 异步回调下游
		 */
		new Thread(new Runnable() {

			@Override
			public void run() {
				while(true){
					try {
						DownRechargeFlow flow = callResultQueue.take();
						logger.info("回调订单:"+flow.getDowonphonenum());
						flow = flowService.findById(flow.getDownorderuuid());
						sendResultDownShop(flow,false);
					} catch (InterruptedException e) {
						e.printStackTrace();
						logger.error(e.getMessage());
					}
				}
			}
		}).start();
	}

	/**
	 * 订单处理
	 */
	private void orderFlow1(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					try {
						DownRechargeFlow flow = RechargeRest.orderQueue.take();
						//查询有没有相等的价格产品 ，再查询上游有没有价格比较低的产品
						//查询运营商 下 省份下 有没有设置渠道产品  渠道商 运营商 省份 业务类型
						//检查订单状态如果是充值中这不处理
						final DownRechargeFlow finalFlow = flowService.findByUUid(flow.getDownorderuuid());
						//只处理 5订单达到状态的订单
						if(finalFlow != null && finalFlow.getStatus() == Config.status[5]){
							try{
								DownShopInfo shop = shopService.findShopInfoByuseruuid(finalFlow.getUserFlow().getUseruuid());
								//检查余额消耗。如果余额小于0 则取反大于授信 就不能继续提单
								if(shop.getDownshopbalance().compareTo(BigDecimal.ZERO) == -1 && Math.abs(shop.getDownshopbalance().intValue())
										>= shop.getCredit().intValue()){
									//订单失败 余额不足
									int tempStatus = finalFlow.getStatus();
									finalFlow.setStatus(Config.status[2]);
									finalFlow.setStatusremark("余额不足");
									Date end = DateUtils.getNowDate();
									finalFlow.setDownendtime(end);
									//finalFlow.setDownreqnum(finalFlow.getDownreqnum() == 0 ? 0 : finalFlow.getDownreqnum() + 1);
									finalFlow.setDownendtimesec(((Long)( end.getTime() - finalFlow.getCreatetime().getTime())).intValue());
									flowService.updateDownrechargeflow(finalFlow);
									sendResultDownShop(finalFlow,true);
								}else{
									taskExecutor.execute(new Runnable() {
										@Override
										public void run() {
											try{
												//扣除下游余额
												flowService.updatedeductionBalance(finalFlow,shop);
												//手动匹配则查询匹配策略
												orderThread.orderHandle(finalFlow);
											}catch (Exception e){
												logger.info("xxx:"+e.getMessage()+":finalFlow:"+finalFlow);
												RechargeRest.orderQueue.add(finalFlow);
											}
										}
									});
								}
							} catch (Exception e){
								logger.info("订单异常,扣除余额失败重新加入队列:"+ (finalFlow == null ? "" : finalFlow.getDowonphonenum())+":,error:"+e.getMessage());
								//e.printStackTrace();
								//扣除余额失败重新加入队列
								RechargeRest.orderQueue.add(finalFlow);
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
						logger.error(e.getMessage());
					}
				}
			}
		}).start();
	}

	private void orderFlow(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					try {
						DownRechargeFlow flow = RechargeRest.orderQueue.take();
						//查询有没有相等的价格产品 ，再查询上游有没有价格比较低的产品
						//查询运营商 下 省份下 有没有设置渠道产品  渠道商 运营商 省份 业务类型
						//检查订单状态如果是充值中这不处理
						final DownRechargeFlow finalFlow = flowService.findByUUid(flow.getDownorderuuid());
						//只处理 5订单达到状态的订单
						if(finalFlow != null && finalFlow.getStatus() == Config.status[5]){
							try{
								DownShopInfo shop = shopService.findShopInfoByuseruuid(finalFlow.getUserFlow().getUseruuid());
								//检查余额消耗。如果余额小于0 则取反大于授信 就不能继续提单
								if(shop.getDownshopbalance().compareTo(BigDecimal.ZERO) == -1 && Math.abs(shop.getDownshopbalance().intValue())
										>= shop.getCredit().intValue()){
									//订单失败 余额不足
									//int tempStatus = finalFlow.getStatus();
									finalFlow.setStatus(Config.status[2]);
									finalFlow.setStatusremark("余额不足");
									Date end = DateUtils.getNowDate();
									finalFlow.setDownendtime(end);
									//finalFlow.setDownreqnum(finalFlow.getDownreqnum() == 0 ? 0 : finalFlow.getDownreqnum() + 1);
									finalFlow.setDownendtimesec(((Long)( end.getTime() - finalFlow.getCreatetime().getTime())).intValue());
									flowService.updateDownrechargeflow(finalFlow);
									sendResultDownShop(finalFlow,true);
								}else{
									//扣除下游余额
									flowService.updatedeductionBalance(finalFlow,shop);

									if(!StringUtils.isBlank(shop.getDownshopnum()) && shop.getDownshopnum().equals(Config.zhqgtask)){
										taskOrder.add(finalFlow);
									}else{
										taskExecutor.execute(new Runnable() {
											@Override
											public void run() {
												orderThread.orderHandle(finalFlow);
											}
										});
									}
								}
							} catch (Exception e){
								logger.info("订单异常2:"+ (finalFlow == null ? "" : finalFlow.getDowonphonenum())+":,error:"+e.getMessage());
								//e.printStackTrace();
								//扣除余额失败重新加入队列
								RechargeRest.orderQueue.add(finalFlow);
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
						logger.error(e.getMessage());
					}
				}
			}
		}).start();
	}

	/**
	 * 核查任务，如果有相同号码 金额则成功 否则 失败
	 */
	public void queryTask(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					try {
						DownRechargeFlow flow = OrderProcessing.taskOrder.take();
						if(flow != null){
							DownShopInfo shop = shopService.findShopInfoByuseruuid(flow.getUserFlow().getUseruuid());
							if(shop != null){
								executeTask(flow,shop);
							}else{
								logger.info("task商户异常:"+flow.getDowonphonenum());
							}
						}else{
							logger.info("task订单为空");
						}
					} catch (Exception e) {
						e.printStackTrace();
						logger.error(e.getMessage());
					}
				}
			}
		}).start();
	}

	/**
	 * 执行任务
	 * @param flow
	 * @param shop
	 */
	public void executeTask(DownRechargeFlow flow,DownShopInfo shop){
		JSONObject body = new JSONObject();
		body.put("appId",flow.getUserFlow().getRemark());
		body.put("mobile",flow.getDowonphonenum());
		body.put("face",flow.getRechargeamount().intValue());
		//升序拼接签名 key=value&key1=value2 最后加上 key=秘钥
		body.put("sign",MD5.md5(StringSort.doSignKey(body)+"appKey="+shop.getDownkey()));
		String result = HttpClient.httpGetUrl(shop.getOrderCallAddress().concat("?").concat(StringSort.jsonToString(body)));
		logger.info("tasksend:"+shop.getOrderCallAddress().concat("?").concat(StringSort.jsonToString(body))+",result:"+result);
		if(!StringUtils.isBlank(result)){
			flow = flowService.findByIdWating(flow.getDownorderuuid());
			JSONObject task = JSONObject.parseObject(result);
			//已经领取
			//tasksend:http://hs.kkshs.com/api/task/mobile?
			// appId=38b495de21b5157dd9418b53bba3e4cc&face=50&mobile=18244242907&
			// sign=fe11e212d2287c6d58af595f276b7b7e,result:
			// {"code":"0","message":null,"data":null,"success":true}

			if(task.containsKey("code") && task.getString("code").equals("0") && !StringUtils.isBlank(task.getString("data"))){
				if(task.getJSONObject("data").containsKey("couponValue") && task.getJSONObject("data").getString("couponValue").equals("1")
				&& flow.getStatus() == Config.status[0]){
					logger.info("核查成功:"+flow.getDowonphonenum()+",面值:"+flow.getRechargeamount().intValue());
					downRechargeFlowRest.successOrder(flow,null,task.getJSONObject("data").getString("taskUid"));
				} else if(flow.getStatus() == Config.status[0] && task.getJSONObject("data").getString("couponValue").equals("0")){
					//失败
					logger.info("核查失败:"+flow.getDowonphonenum()+",面值:"+flow.getRechargeamount().intValue());
					downRechargeFlowRest.orderFailt(flow,null,"任务未领取");
				} else {
					flow.setRemark("订单状态异常");
					flowService.addOrderMsg(flow);
				}
			} else if(task.containsKey("code") && !task.getString("code").equals("0")){
				//失败
				downRechargeFlowRest.orderFailt(flow,null,task.getString("message"));
			}else{
				logger.info("task任务异常:"+result);
				flow.setRemark(task.getString("message"));
				flowService.addOrderMsg(flow);
			}
		}else{
			logger.info("任务接口异常:"+shop.getDownshopnum());
		}
	}

	public static void main(String[] args) {
		DownRechargeFlow flow = new DownRechargeFlow(){{
			setDowonphonenum("18782435842");
			setRechargeamount(new BigDecimal("100"));
			setUserFlow(new User(){{
				setRemark("38b495de21b5157dd9418b53bba3e4cc");
			}});
		}};
		DownShopInfo shop = new DownShopInfo(){{
			setOrderCallAddress("http://hs.kkshs.com/api/task/mobile");
			setDownkey("78e7998b21a854a8049fbfdaac0ace88");
		}};
		new OrderProcessing().executeTask(flow,shop);
	}

	private void orderFlow2(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				while(true){
					try {
						DownRechargeFlow flow = RechargeRest.orderQueue.take();
						//查询有没有相等的价格产品 ，再查询上游有没有价格比较低的产品
						//查询运营商 下 省份下 有没有设置渠道产品  渠道商 运营商 省份 业务类型
						taskExecutor.execute(new Runnable() {
							@Override
							public void run() {
								//检查订单状态如果是充值中这不处理
								final DownRechargeFlow finalFlow = flowService.findByUUid(flow.getDownorderuuid());
								//只处理 5订单达到状态的订单
								if(finalFlow != null && finalFlow.getStatus() == Config.status[5]){
									try{
										DownShopInfo shop = shopService.findShopInfoByuseruuid(finalFlow.getUserFlow().getUseruuid());
										//检查余额消耗。如果余额小于0 则取反大于授信 就不能继续提单
										if(shop.getDownshopbalance().compareTo(BigDecimal.ZERO) == -1 && Math.abs(shop.getDownshopbalance().intValue())
												>= shop.getCredit().intValue()){
											//订单失败 余额不足
											int tempStatus = finalFlow.getStatus();
											finalFlow.setStatus(Config.status[2]);
											finalFlow.setStatusremark("余额不足");
											Date end = DateUtils.getNowDate();
											finalFlow.setDownendtime(end);
											//finalFlow.setDownreqnum(finalFlow.getDownreqnum() == 0 ? 0 : finalFlow.getDownreqnum() + 1);
											finalFlow.setDownendtimesec(((Long)( end.getTime() - finalFlow.getCreatetime().getTime())).intValue());
											flowService.updateDownrechargeflow(finalFlow);
											sendResultDownShop(finalFlow,true);
										}else{
//									try{
											//扣除下游余额
											flowService.updatedeductionBalance(finalFlow,shop);
											orderThread.orderHandle(finalFlow);
										}
									} catch (Exception e){
										logger.info("订单异常2:"+ (finalFlow == null ? "" : finalFlow.getDowonphonenum())+":,error:"+e.getMessage());
										e.printStackTrace();
										//扣除余额失败重新加入队列
										RechargeRest.orderQueue.add(finalFlow);
									}
								}
							}
						});
					} catch (Exception e) {
						e.printStackTrace();
						logger.error(e.getMessage());
					}
				}
			}
		}).start();
	}

	/**
	 * 青海移动检查
	 */
	private void qhyd(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true){
					try {
						YiDongEntity yiDongEntity = OrderProcessing.yiDongQueue.take();
						if(yiDongEntity != null){
							UpOrder upOrder = upOrderService.findByCallId(yiDongEntity.getOrderId());
							if(upOrder != null && upOrder.getStatus() == Config.status[0]){
								qingHaiYd.rechargeYidong(yiDongEntity,upOrder);
							}else{
								logger.info("青海订单异常1:"+upOrder.getUpphonenum());
							}
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	/**
	 * 青海移动下单
	 */
	private void placeOrder(){
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true){
					try {
						YiDongEntity yiDongEntity = OrderProcessing.yiDongQueuePlace.take();
						if(yiDongEntity != null){
							UpOrder upOrder = upOrderService.findByCallId(yiDongEntity.getOrderId());
							if(upOrder != null && upOrder.getStatus() == Config.status[0]){
								qingHaiYd.placeOrder(yiDongEntity,upOrder);
							}else{
								logger.info("青海订单异常2:"+upOrder.getUpphonenum());
							}
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}).start();
	}

	/**
	 * 发送回调到下游
	 * @param flows
	 */
	public void sendResultDownShop(final DownRechargeFlow flows,boolean temp){
		try{
			sendDownMsg(flows,temp);
			//CallOrder order = callOrderService.findById(flows.getDownorderuuid());
			//if(order == null){
			//	CallOrder callOrder = new CallOrder();
			//	callOrder.setCallNum(0);
			//	callOrder.setCallStatus(0);
			//	callOrder.setCallTime(new Date());
			//	callOrder.setOrderId(flows.getDownorderuuid());
			//	callOrderService.saveOrder(callOrder);
			//	sendDownMsg(flows,temp);
			//}else if (DateUtils.addMinutes(3,order.getCallTime()).getTime() < new Date().getTime() || temp){
			//	order.setCallTime(new Date());
			//	//更新调用时间
			//	this.callOrderService.updateCall(order);
			//	sendDownMsg(flows,temp);
			//}
		}catch (Exception e){
			e.printStackTrace();
			logger.info("发送失败:"+flows.getDowonphonenum());
		}
	}

	void sendDownMsg(final DownRechargeFlow flows,boolean temp){
		taskExecutor.execute(new Runnable() {
			@Override
			public void run() {
				final com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
				DownShopInfo shopInfo = shopService.findShopInfoByUuid(flows.getUserFlow().getUseruuid());
				if(shopInfo != null){
					switch (shopInfo.getDownshopnum()){
						case Config.jingheng:
							sendDownJenghengInfo(json,shopInfo,flows,temp);
							break;
						case Config.yisai:
							sendDownYiSaiInfo(json,shopInfo,flows,temp);
							break;
						default:
							sendDownInfo(json,shopInfo,flows,temp);
							break;
					}
				}
			}
		});
	}

	private void sendDownYiSaiInfo(final JSONObject out,final DownShopInfo shopInfo,final DownRechargeFlow flows,boolean temp){
		DownRechargeFlow flow = flowService.findById(flows.getDownorderuuid());

//		partnerid n int 合作伙伴在平台的用户编号(不是用户登录名).登录平台后可查询.如 200000
//		esupordernumber n string 平台订单号
//		provideordernumber y string 供货商订单号
//		time n string 响应时间（格式 yyyy-MM-dd HH:mm:ss）
//		status n Int 订单状态，见附录 b
//		finishedtime y string 订单完成时间(订单状态为最终结果时必填) （格式 yyyy-MM-dd HH:mm:ss）
//		timestamp n string 时间戳（格式 yyyy-MM-dd HH:mm:ss）
		out.put("partnerid",shopInfo.getOrderCallAddress());
		out.put("result", "t");
		out.put("esupordernumber", flows.getDownreqid());
		out.put("provideordernumber", flow.getDownorderuuid());
		out.put("time", DateUtils.toLongDate(DateUtils.getNowDate()));
		out.put("status", flow.getStatus() == 2 ? 4 : flow.getStatus() == 3 ? 5 : 0);
		out.put("finishedtime",DateUtils.toLongDate(DateUtils.getNowDate()));
		out.put("timestamp",DateUtils.toLongDate(DateUtils.getNowDate()));
		final JSONObject resultdata = new JSONObject();
		resultdata.put("payresult", flow.getStatus() == 2 ? URLEncoder.encode(flow.getRemark()) : "失败");
		out.put("resultdata",resultdata.toString());
		out.put("sign", MD5.md5(StringSort.doSign(out).concat(shopInfo.getUser().getRemark())));
		try{
			if(flow.getStatus() == 2 || flow.getStatus() == 3){
				logger.info("sendDownYiSaiInfo:"+flow.getDownnotificationaddress().concat("?").concat(StringSort.jsonToString(out)));
				if(!StringUtils.isBlank(flow.getDownnotificationaddress()) && (flow.getCallNum() < Config.callBack || temp)){
					String result = HttpClient.postUrlFrom(flow.getDownnotificationaddress(),StringSort.jsonToString(out));

					logger.info("sendDownYiSaiInfo:"+result+",电话:"+flow.getDowonphonenum());

					if(!StringUtils.isBlank(result) && (result.contains("Status") || result.contains("通知成功"))){
						//callOrderService.deleteOrder(flow.getDownorderuuid());
						if(flowService.updateDownrechargeflow(flow, Config.callStatus[1],flow.getCallNum())){
							logger.info("update_flow_call_statu:"+flow.getDowonphonenum());
						}
					}
				}else{
					if(flow.getCallNum() >= Config.callBack){
						//callOrderService.deleteOrder(flow.getDownorderuuid());
						//超过次数后不在回调
						flowService.updateDownrechargeflow(flow, Config.callStatus[1],flow.getCallNum());
					}
					logger.error("回调地址为空或超出回调次数:"+flow.getDowonphonenum()+","+flow.getDownorderuuid());
				}
			}else{
				logger.info("添加到回调队列:"+flow.getDowonphonenum());
				callResultQueue.add(flow);
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage()+","+out.toString());
			logger.info("call method failt,add call queue:"+flow.getDowonphonenum()+","+e.getMessage());
			if(e.getMessage().equals("Target host is null")){
				//目标地址为空不在回调
				//callOrderService.deleteOrder(flow.getDownorderuuid());
				flowService.updateDownrechargeflow(flow, Config.callStatus[1],flow.getCallNum());
			}else if(flow.getCallNum() < Config.callBack ){
				callResultQueue.add(flow);
			}
		}
	}


	/**
	 * 字段名	必填	说明
	 * userId	是	合作方用户编号(充值平台方提供)
	 * bizId	是	业务编号
	 * ejId	是	充值平台方订单号
	 * downstreamSerialno	是	合作方商户系统的流水号
	 * voucher	选	凭证流水  不参与签名
	 * voucherType	选	凭证类型  【文档底部详解】不参与签名
	 * status	是	状态 2 是成功 3 是失败
	 * sign	是	签名(MD5) sign=MD5(bizId+downstreamSerialno+ejId+ status + userId + privatekey);
	 * @param json
	 * @param shopInfo
	 */
	private void sendDownJenghengInfo(final JSONObject json,final DownShopInfo shopInfo,final DownRechargeFlow flows,boolean temp){
		DownRechargeFlow flow = flowService.findById(flows.getDownorderuuid());

		json.put("userId", shopInfo.getUser().getUseruuid());
		json.put("bizId", flow.getDownShopProduct().getDownfacevalue());
		json.put("ejId", flow.getDownorderuuid());
		json.put("downstreamSerialno", flow.getDownreqid());
		json.put("status", flow.getStatus());

		json.put("sign", MD5.md5(StringSort.doSignValue(json).concat(shopInfo.getDownkey())));
		if(flow.getStatus() == 2){
			json.put("voucherType","0");
			json.put("voucher", flow.getRemark() == null ? "failt" : UrlEncoded.encodeString(flow.getRemark()));
		}
		try{
			if(flow.getStatus() == 2 || flow.getStatus() == 3){
				logger.info("sendDownJenghengInfo:"+flow.getDownnotificationaddress().concat("?").concat(StringSort.jsonToString(json)));
				if(!StringUtils.isBlank(flow.getDownnotificationaddress()) && (flow.getCallNum() < Config.callBack || temp)){
					String result = HttpClient.httpGetUrl(flow.getDownnotificationaddress().concat("?").concat(StringSort.jsonToString(json)));

					logger.info("sendDownJenghengInfo:"+result+",电话:"+flow.getDowonphonenum());
					if(!StringUtils.isBlank(result) && (result.equals("0") || result.equals("success") || result.equals("ok"))){
						//callOrderService.deleteOrder(flow.getDownorderuuid());
						if(flowService.updateDownrechargeflow(flow, Config.callStatus[1],flow.getCallNum()+1)){
							logger.info("update_flow_call_statu:"+flow.getDowonphonenum());
						}
					}else{
						//失败时加入 失败回调队列
						if(flow.getCallNum() < Config.callBack){
							callResultQueue.add(flow);
						}
						logger.error("调用失败_回调错误:"+flow.getDowonphonenum());
					}
				}else{
					if(flow.getCallNum() >= Config.callBack){
						//callOrderService.deleteOrder(flow.getDownorderuuid());
						//超过次数后不在回调
						flowService.updateDownrechargeflow(flow, Config.callStatus[1],flow.getCallNum());
					}
					logger.error("回调地址为空或超出回调次数:"+flow.getDowonphonenum()+","+flow.getDownorderuuid());
				}
			}else{
				logger.info("添加到回调队列:"+flow.getDowonphonenum());
				callResultQueue.add(flow);
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage()+","+json.toString());
			logger.info("call method failt,add call queue:"+flow.getDowonphonenum()+","+e.getMessage());
			if(e.getMessage().equals("Target host is null")){
				//目标地址为空不在回调
				//callOrderService.deleteOrder(flow.getDownorderuuid());
				flowService.updateDownrechargeflow(flow, Config.callStatus[1],flow.getCallNum());
			}else if(flow.getCallNum() < Config.callBack ){
				callResultQueue.add(flow);
			}
		}
	}

	/**
	 * 系统默认回调
	 * @param json
	 * @param shopInfo
	 */
	private void sendDownInfo(final JSONObject json,final DownShopInfo shopInfo,final DownRechargeFlow flow,boolean temp){
		//DownRechargeFlow flow = flowService.findById(flows.getDownorderuuid());

		json.put("orderNum", flow.getDownorderuuid());//平台id
		json.put("status", flow.getStatus());//== Config.status[1] ?  flow.getStatus() : Config.status[0]
		json.put("orderId", flow.getDownreqid());
		json.put("createTime", flow.getCreatetime().getTime() / 1000);
		//中文编码
		json.put("msg", flow.getRemark() == null ? "" : UrlEncoded.encodeString(flow.getRemark()) );
		json.put("sign", MD5.md5(StringSort.doSign(json).concat("&key="+shopInfo.getDownkey())));
		try{
			if(flow.getStatus() == 2 || flow.getStatus() == 3){
				logger.info("sendDownShop:"+json.toString()+":"+flow.getDowonphonenum());
				if(!StringUtils.isBlank(flow.getDownnotificationaddress()) && (flow.getCallNum() < Config.callBack || temp)){
					String result = HttpClient.post(flow.getDownnotificationaddress(), json.toString());

					logger.info("sendResultDownShop:"+result+",电话:"+flow.getDowonphonenum());
					if(!StringUtils.isBlank(result) && (result.equals("0") || result.equals("1") || result.equals("ok") || result.equals("fail"))){
						//callOrderService.deleteOrder(flow.getDownorderuuid());
						if(flowService.updateDownrechargeflow(flow, Config.callStatus[1],flow.getCallNum()+1)){
							logger.info("update_flow_call_statu:"+flow.getDowonphonenum());
						}
					}else{
						logger.error("调用失败_回调错误:"+flow.getDowonphonenum());
						flowService.updateDownrechargeflow(flow, Config.callStatus[1],flow.getCallNum()+1);
					}
				}else{
					if(flow.getCallNum() >= Config.callBack){
						//callOrderService.deleteOrder(flow.getDownorderuuid());
						//超过次数后不在回调
						flowService.updateDownrechargeflow(flow, Config.callStatus[1],flow.getCallNum());
					}else{
						flowService.updateDownrechargeflow(flow, Config.callStatus[1],flow.getCallNum() + 1);
					}
					logger.error("回调地址为空或超出回调次数:"+flow.getDowonphonenum()+","+flow.getDownorderuuid()+","+flow.getCallNum());
				}
			}else{
				logger.info("添加到回调队列:"+flow.getDowonphonenum());
				callResultQueue.add(flow);
			}
		}catch(Exception e){
			e.printStackTrace();
			logger.error(e.getMessage()+","+json.toString());
			logger.info("call method failt,add call queue:"+flow.getDowonphonenum()+","+e.getMessage());
			if(e.getMessage().equals("Target host is null")){
				//目标地址为空不在回调
				//callOrderService.deleteOrder(flow.getDownorderuuid());
				flowService.updateDownrechargeflow(flow, Config.callStatus[1],flow.getCallNum());
			}else if(flow.getCallNum() < Config.callBack ){
				callResultQueue.add(flow);
			}
		}
	}
}
